﻿<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <template>
        <div class="hello">
            <input type="text" placeholder="请输入用户名" v-model="nameTxt1" />
            <input type="text" placeholder="请输入内容" v-model="valueTxt1" />
            <button @click="ttttt()">测试连接</button>
            <button @click="closeasdasd()">测试关闭</button>
            <button @click="load()">测试重新连接</button>
            <div>
                后端返回数据：<span>{{ msg }}</span>
            </div>
        </div>
    </template>

    <script>
        import * as SignalR from '@microsoft/signalr'
        import Vue from 'vue'
        import { ACCESS_TOKEN } from '@/store/mutation-types'
        //需要自己安装 SignalR 
        export default {
            data() {
                return {
                    msg: undefined,
                    nameTxt1: undefined,
                    valueTxt1: undefined,
                    connection: undefined
                }
            },

            created() {
                this.connection = new SignalR.HubConnectionBuilder()
                    .configureLogging(SignalR.LogLevel.Information)
                    .withUrl(`/chathub/chathub`, {
                        accessTokenFactory: () => Vue.ls.get(token) // 传递token 、也可以无需传递token
                    })
                    .build()

                this.load()
                //（给服务器端调用，需要在methods中定义）
                this.connection.on('ReceiveMessage', this.smgtest)
            },
            methods: {
                //服务器端调用
                smgtest(data) {
                    this.msg = data
                },
                //发送
                ttttt() {
                    //客户端调用服务端SendMessage方法
                    this.connection.invoke('SendMessage', '394584716271697').catch(function (err) {
                        return console.error(err.toString())
                    })
                },
                //关闭连接--退出时调用
                closeasdasd() {
                    this.connection.stop().then(() => {
                        console.log('关闭')
                    })
                },
                load() {
                    // 开始连接
                    this.connection
                        .start()
                        .then(function () {
                            console.log('自定义SignalR连接成功')
                        })
                        .catch(function (err) {
                            return console.error('自定义SignalR失败失败失败失败', err.toString())
                        })
                }
            }
        }
    </script>
</body>
</html>